/* eslint-disable max-lines-per-function */
/**
 * @Creator: fenglingxia
 * @Date: 2020/3/18
 * 用户特征-终端及机型分布
 */
import React, {useContext, useState, useEffect} from 'react';
import {Table, Empty} from 'antd';
import {getUserFeatureFields} from '~/service/performance';
import {generatePieData} from '../../utils';
import PieComponent from '../PieComponent';
import BarComponent from '../BarComponent';
import {generateBasicParam, StoreContext} from '../data';
import {USER_FEATURE_ACTION_TYPES} from '../utils';
import './index.styl';

export default () => {
    const {state, dispatch} = useContext(StoreContext);
    const {osSearchResult, osVersionSearchResult, brandVersionSearchResult, osAndNetLoading, osSelectedField} = state;
    // 定义表头
    const USER_FEATURE_OS_VERSION_TABLE_HEAD
        = [
            {
                title: '系统版本',
                dataIndex: 'field',
                key: 'field_version'
            },
            {
                title: '人次',
                dataIndex: 'pv',
                key: 'pv_version'
            },
            {
                title: '占比',
                dataIndex: 'percent',
                key: 'percent_version'
            }

        ];
    const USER_FEATURE_MACHINE_TYPE_TABLE_HEAD
        = [
            {
                title: '机型',
                dataIndex: 'field',
                key: 'field_type'
            },
            {
                title: '人次',
                dataIndex: 'pv',
                key: 'pv_type'
            },
            {
                title: '占比',
                dataIndex: 'percent',
                key: 'percent_type'
            }
        ];

    // 定义操作系统和机型的pie的dataSource的状态
    const [osDataSource, setOsDataSource] = useState([]);

    useEffect(() => {
        setOsDataSource(generatePieData(osSearchResult));
    }, [osSearchResult]);

    // 定义下钻时调用的函数，name代表下钻的os，flag代表是否添加StringFilter掺乎
    const getData = (name, flag) => {
        let allFields = [
            {
                ...generateBasicParam(state),
                field: 'os_version',
                top: 10
            },
            {
                ...generateBasicParam(state),
                field: 'brand_version',
                top: 10
            }
        ];
        if (flag) {
            allFields = allFields.map(item => Object.assign(item, {stringFilter: {field: 'os', value: name}}));
        }
        (async () => {
            const filedValues = await Promise.all(allFields.map(getUserFeatureFields));
            const toStore = [
                'osVersionSearchResult',
                'brandVersionSearchResult'
            ]
                .reduce((result, key, index) => ({
                    ...result,
                    [key]: filedValues[index] && filedValues[index].data && filedValues[index].data.userFields,
                }), {});
            for (const key in toStore) {
                toStore[key] = toStore[key].map((item, index) => ({
                    ...item,
                    percent: `${item.percent}%`,
                    key: key.substring(0, 5) + index
                }));
            }
            dispatch({
                type: USER_FEATURE_ACTION_TYPES.REGULAR_UPDATE,
                payload: {
                    ...toStore,
                    osAndNetLoading: false
                },
            });
        })();
    };

    function pieClickCallback(params) {
        // 当点击pie时，设置页面为loading状态
        dispatch({
            type: USER_FEATURE_ACTION_TYPES.REGULAR_UPDATE,
            payload: {
                osAndNetLoading: true
            },
        });
        // 定义函数：当前没有选中项或者选中项不等于点击项时调用
        function getClickedItem() {
            const tempArr = osSearchResult.reduce((res, item) => {
                if (item.field === params.data.name) {
                    item.selected = true;
                }
                return [...res, item];
            }, []);
            dispatch({
                type: USER_FEATURE_ACTION_TYPES.REGULAR_UPDATE,
                payload: {
                    osSearchResult: tempArr

                }
            });
            getData(params.data.name, true);
        }
        // 找出当前选中项
        const osSelectedItem = osSearchResult.find(item => item.selected === true);
        // 判断当前是否有已选中的项
        if (osSelectedItem) {
            const tempArr = osSearchResult.reduce((res, item) => {
                if (item.field === osSelectedItem.field) {
                    item.selected = false;
                }
                return [...res, item];
            }, []);
            dispatch({
                type: USER_FEATURE_ACTION_TYPES.REGULAR_UPDATE,
                payload: {
                    osSearchResult: tempArr

                }
            });
            // 如果当前已有选中项，判断当前点击的项是否是已选中的项，如果是的话，则重新加载所有数据；否则加载点击项的数据
            if (osSelectedItem.field === params.data.name) {
                getData(params.data.name, false);
                // 当点击已选中的项时，加载所有数据，下钻字段设置为空
                dispatch({
                    type: USER_FEATURE_ACTION_TYPES.REGULAR_UPDATE,
                    payload: {
                        osSelectedField: ''
                    }
                });
            }
            else {
                // 当点击其他项时，加载该OS下数据，下钻字段设置为该OS
                dispatch({
                    type: USER_FEATURE_ACTION_TYPES.REGULAR_UPDATE,
                    payload: {
                        osSelectedField: params.data.name
                    }
                });
                getClickedItem();
            }
        }
        else {
            // 当点击其他项时，加载该OS下数据，下钻字段设置为该OS
            dispatch({
                type: USER_FEATURE_ACTION_TYPES.REGULAR_UPDATE,
                payload: {
                    osSelectedField: params.data.name
                }
            });
            getClickedItem();
        }
    }

    return (
        <div className="terminalType_container">
            <div className="item">
                <div>
                    <h3>操作系统</h3>
                    {(osDataSource.length === 0 && !osAndNetLoading) ? (
                        <Empty imageStyle={{height: 70}} image={Empty.PRESENTED_IMAGE_SIMPLE} />
                    ) : (
                        <PieComponent
                            title="操作系统"
                            dataSource={osDataSource}
                            pieClickCallback={pieClickCallback}
                        />
                    )}
                </div>
            </div>
            <hr className="line" />
            <div className="item">
                <div>
                    <h3>
                        系统版本top10
                    </h3>
                    {
                        osSelectedField
                            ? (
                                <p>
                                    <span className="line">|</span>
                                    <span>
                                        {osSelectedField}
                                    </span>
                                </p>
                            )
                            : (null)
                    }
                    {(osVersionSearchResult.length === 0 && !osAndNetLoading) ? (
                        <Empty imageStyle={{height: 70}} image={Empty.PRESENTED_IMAGE_SIMPLE} />
                    ) : (
                        <BarComponent title="os" dataList={osVersionSearchResult} />
                    )}
                </div>
                <Table
                    className="table"
                    columns={USER_FEATURE_OS_VERSION_TABLE_HEAD}
                    dataSource={osVersionSearchResult}
                    pagination={false}
                    size="small"
                    bordered={false}
                    loading={osAndNetLoading}
                />
            </div>
            <hr className="line" />
            <div className="item">
                <div>
                    <h3>
                        机型top10
                    </h3>
                    {
                        osSelectedField
                            ? (
                                <p>
                                    <span className="line">|</span>
                                    <span>
                                        {osSelectedField}
                                    </span>
                                </p>
                            )
                            : (null)
                    }
                    {(brandVersionSearchResult.length === 0 && !osAndNetLoading) ? (
                        <Empty imageStyle={{height: 70}} image={Empty.PRESENTED_IMAGE_SIMPLE} />
                    ) : (
                        <BarComponent type="type" dataList={brandVersionSearchResult} />
                    )}
                </div>
                <Table
                    className="table"
                    columns={USER_FEATURE_MACHINE_TYPE_TABLE_HEAD}
                    dataSource={brandVersionSearchResult}
                    pagination={false}
                    size="small"
                    bordered={false}
                    loading={osAndNetLoading}
                />
            </div>
        </div>
    );
};
